package com.milkshopbackend.milkshop.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    private static final Logger logger = LoggerFactory.getLogger(WebConfig.class);

    @Value("${upload.path}")
    private String uploadPath;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 兼容绝对路径和相对路径
        String path = uploadPath.replace("\\", "/");
        logger.info("Original upload path: {}", path);

        // 如果是以 /uploads/avatar 或 uploads/avatar 结尾，去掉 /avatar，映射整个 uploads 目录
        if (path.endsWith("/avatar")) {
            path = path.substring(0, path.lastIndexOf("/avatar"));
        }
        
        // 如果是相对路径，补全为绝对路径
        if (!path.startsWith("/") && !path.contains(":/")) {
            path = System.getProperty("user.dir") + "/" + path;
        }

        String finalPath = "file:" + path + "/";
        logger.info("Static resource mapping: /uploads/** -> {}", finalPath);
        
        // 最终映射
        registry.addResourceHandler("/uploads/**")
                .addResourceLocations(finalPath);
    }
} 